<?php

namespace Cohuna\Controllers;

use Cohuna\Models\CohunaMerchantPay;
use Cohuna\Models\CohunaPay;
use Cohuna\Paginator\PaginatorArray;
use Cohuna\Services\CohunaMerchantService;
use Cohuna\Services\CohunaPayService;

class HomeController extends ControllerBase
{
    public function indexAction()
    {
        $this->dispatcher->forward(array('controller'=>'Home','action'=>'list'));
    }

    /**
     * 支付列表
     */
    public function listAction()
    {
        $page = max(intval($this->request->getQuery('page')),1);

        $offset = ($page - 1) * self::PageSize;

        $list = CohunaPay::find(array(
            'is_delete = 0',
            'offset' => intval($offset),
            'limit' => self::PageSize,
            'order' => 'id DESC'
        ));

        $paginator = new PaginatorArray([
            'data'          => $list,
            'limit'         => self::PageSize,
            'current'          => $page,
            'total_items'   => CohunaPay::count(),
            'href'          => '/qualification/list'
        ]);
        $this->view->setVar('Model',$paginator);
    }

    /**
     * 编辑或添加支付
     */
    public function editAction()
    {
        $payment_platform_list = array();
        $payment_gateway_list = array();
        $encryption_list = array();
        foreach ($this->config['payment_platform_list'] as $code=>$platform){
            $payment_platform_list[] = array('name'=>$platform['name'],'code'=>$code);
            $gateway_list = array();
            foreach ($platform['gateway_list'] as $gateway=>$gateway_item){
                $gateway_list[] = array('name'=>$gateway_item['name'],'code'=> $gateway);
                $encryption = array();
                foreach ($gateway_item['encryption_list'] as $key=>$encry){
                    $encryption[] = array('name' => $encry,'code'=>$key);
                }
                $encryption_list[$code . '_' . $gateway] = $encryption;
            }
            $payment_gateway_list[$code] = $gateway_list;
        }

        $this->view->setVar('payment_platform_list', json_encode($payment_platform_list,JSON_UNESCAPED_UNICODE));
        $this->view->setVar('payment_gateway_list', json_encode($payment_gateway_list,JSON_UNESCAPED_UNICODE));
        $this->view->setVar('encryption_list', json_encode($encryption_list,JSON_UNESCAPED_UNICODE));

        $pay_id = trim($this->request->getQuery('pay_id'));
        $step = intval($this->request->getQuery('step'));
        $payment_platform = trim($this->request->get('payment_platform'));
        $payment_gateway = trim($this->request->get('payment_gateway'));
        $encryption = trim($this->request->get('encryption'));
        $merchant_id = trim($this->request->get('mch_id'));

        //如果商户不存在，则返回404
        if($this->request->isGet() && (empty($merchant_id) || !CohunaMerchantService::getInstance()->exist($merchant_id))){
            return $this->dispatcher->forward(array('controller'=>'Error','action'=>'show404'));
        }
        $this->view->setVar('merchant_id',$merchant_id);

        if(!isset($this->config['payment_platform_list'][$payment_platform]) ||
            !isset($this->config['payment_platform_list'][$payment_platform]['gateway_list'][$payment_gateway]) ||
            !isset($this->config['payment_platform_list'][$payment_platform]['gateway_list'][$payment_gateway]['encryption_list'][$encryption])){
            $step = 0;
        }

        if($this->request->isPost()) {
            $cohuna_pay = new CohunaPay();
            $data = $this->request->getPost();
            if(empty($data['pay_platform'])){
                return $this->response->setJsonContent(array('errCode'=>50002,'errMsg' => '支付平台不能为空'))->send();
            }elseif (empty($data['gateway'])){
                return $this->response->setJsonContent(array('errCode'=>50002,'errMsg' => '支付网关'))->send();
            }elseif (empty($data['sign_type'])){
                return $this->response->setJsonContent(array('errCode'=>50002,'errMsg' => '加密方式'))->send();
            }elseif (!isset($data['pay_name']) || empty(trim($data['pay_name']))){
                return $this->response->setJsonContent(array('errCode'=>50002,'errMsg' => '支付名称不能为空'))->send();
            }
            if(empty($pay_id)){
               $data['pay_id'] = CohunaPay::createPayId();
            }else{
                $obj = CohunaPay::findFirst(array('pay_id=:pay_id:','bind'=>['pay_id'=>$pay_id]));
                if(empty($obj)){
                    return $this->response->setJsonContent(array('errCode'=>50003,'errMsg' => '支付配置不存在'))->send();
                }
                $data['id'] = $obj->id;
            }
            $data['merchant_id'] = $merchant_id;

            $result = $cohuna_pay->save($data);
            if($result){
                return $this->response->setJsonContent(array('errCode'=>0,'errMsg' => '保存成功','pay_id' => $cohuna_pay->pay_id))->send();
            }
            return $this->response->setJsonContent(array('errCode'=>50002,'errMsg' => '保存失败'))->send();
        }

        if(empty($pay_id)){
            if($step == 0){
                $this->view->pick('home/pay_select');
            }elseif ($step == 1){
                $payment_type = $this->config['payment_platform_list'][$payment_platform]['name'] . ' &gt; ' . $this->config['payment_platform_list'][$payment_platform]['gateway_list'][$payment_gateway]['name'] . ' &gt; ' .
                    $this->config['payment_platform_list'][$payment_platform]['gateway_list'][$payment_gateway]['encryption_list'][$encryption];

                $this->view->setVars(array(
                    'payment_config_id' => $pay_id,
                    'payment_platform'=>$payment_platform,
                    'payment_gateway'=>$payment_gateway,
                    'encryption'=>$encryption,
                    'payment_type' => $payment_type,
                    'encryption_name' => $this->config['payment_platform_list'][$payment_platform]['gateway_list'][$payment_gateway]['encryption_list'][$encryption]
                ));

                $this->view->pick('home/pay_edit');
            }
        }
    }

    /**
     * 支付方式详情
     */
    public function detailAction()
    {
        $pay_id = trim($this->request->getQuery('pay_id'));

        $cohuna_pay =  CohunaPay::findFirst(array('pay_id=:pay_id: AND is_delete = 0','bind'=>['pay_id'=>$pay_id]));

        $this->view->setVar('Model',$cohuna_pay);
    }

    /**
     * 修改密钥
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function editEncryptionAction()
    {
        $pay_id = trim($this->request->getPost('pay_id'));
        $encrypt = trim($this->request->getPost('encryption'));
        $field = trim($this->request->getPost('field'));

        $cohuna_pay = CohunaPay::findFirst(array('pay_id=:pay_id: AND is_delete = 0','bind'=>array('pay_id'=>$pay_id)));

        if(empty($cohuna_pay)){
            return $this->response->setJsonContent(array('errCode'=>50001,'errMsg'=>'配置不存在'))->send();
        }
        $cohuna_pay->pay_config[$field] = $encrypt;

        $result = $cohuna_pay->save();
        if($result){
            return $this->response->setJsonContent(array('errCode'=>0,'errMsg'=>'保存成功'))->send();
        }
        return $this->response->setJsonContent(array('errCode'=>50002,'errMsg' => '保存失败'))->send();
    }

    /**
     * 编辑支付配置信息
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function editPayAction()
    {
        $pay_id = trim($this->request->getPost('pay_id'));
        $pay_name = trim($this->request->getPost('pay_name'));
        $pay_status = trim($this->request->getPost('pay_status'));
        $remark = trim($this->request->getPost('remark'));

        $cohuna_pay = CohunaPay::findFirst(array('pay_id=:pay_id: AND is_delete = 0','bind'=>array('pay_id'=>$pay_id)));

        if(empty($cohuna_pay)){
            return $this->response->setJsonContent(array('errCode'=>50001,'errMsg'=>'配置不存在'))->send();
        }
        if(empty($pay_name) || strlen($pay_name) > 100){
            return $this->response->setJsonContent(array('errCode'=>50001,'errMsg'=>'配置名称不能为空且必须小于100字'))->send();
        }
        if(strlen($remark) > 1000){
            return $this->response->setJsonContent(array('errCode'=>50001,'errMsg'=>'配置描述必须小于1000字'))->send();
        }
        $cohuna_pay->pay_name = $pay_name;
        $cohuna_pay->pay_status = $pay_status == 'y' ? 'y' : 'n';
        $cohuna_pay->remark = $remark;

        $result = $cohuna_pay->save();


        if($result){
            $data = array();
            $data['pay_name'] = $pay_name;
            $data['remark'] = $remark;
            $data['pay_status'] = $pay_status == 'y' ? '启用' : '禁用';
            $data['errCode'] = 0;
            $data['errMsg'] = '保存成功';
            return $this->response->setJsonContent($data)->send();
        }
        return $this->response->setJsonContent(array('errCode'=>50002,'errMsg' => '保存失败'))->send();
    }

    public function deleteAction()
    {
        $pay_id = trim($this->request->get('pay_id'));
        $mch_id = trim($this->request->get('merchant_id'));

        if (empty($pay_id)) {
            if ($this->request->isAjax()) {
                return $this->response->setJsonContent(array('errCode' => 50001, 'errMsg' => '数据不存在'))->send();
            } else {
                return $this->dispatcher->forward(array('controller' => 'Error', 'action' => 'show404'));
            }
        }
        if (CohunaPayService::getInstance()->delete($pay_id,$mch_id)) {
            if ($this->request->isAjax()) {
                return $this->response->setJsonContent(array('errCode' => 0, 'errMsg' => '删除成功'))->send();
            } else {
                return $this->response->redirect($this->url->get('home/list'));
            }
        } else {
            if ($this->request->isAjax()) {
                return $this->response->setJsonContent(array('errCode' => 50001, 'errMsg' => '删除失败'))->send();
            } else {
                return $this->dispatcher->forward(array('controller' => 'Error', 'action' => 'show500'));
            }
        }

    }
}